import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer,
    ProTable,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Tag, Switch, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import type {FormValueType} from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import AddForm from './components/AddForm';
import type {UserListItem, UserListPagination} from './data';
import {
    addUser,
    fUserList,
    editUser,
    changeStatus,
    userDelete,
    resetPassword,
    syncLdap
} from './service';
import {UserStatusEnum} from "@/pages/data.enum";
import {organizationSelectList} from "@/pages/organization/org-list/service";
import './user.less';
import {useAccess, Access} from 'umi';

const {confirm} = Modal;

const handleSwitch =  (currentRow?: UserListItem) => {
    const hide = message.loading('正在修改');
    let userId = currentRow?.userid || ''
    let status = currentRow?.status || 0


    try {
        if (status == 1) {
            changeStatus({userid:userId, status:2});
        }
        if (status == 2) {
            changeStatus({userid:userId, status:1});
        }

        hide();
        message.success('修改成功');

        return true;
    } catch (error) {
        hide();
        message.error('修改失败请重试！');
        return false;
    }
}

const handleAdd = async (fields: UserListItem) => {
    const hide = message.loading('正在添加');

    try {
        await addUser({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};

const handleUpdate = async (fields: FormValueType, currentRow?: UserListItem) => {
    const hide = message.loading('正在配置');

    try {
        await editUser({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};

const handleRemove = async (selectedRows: UserListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await userDelete({
            userIds: selectedRows.map((row) => row.userid),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const handleSyncLdap = async (selectedRows: UserListItem[]) => {
    const hide = message.loading('正在同步');
    if (!selectedRows) return true;

    try {
        await syncLdap({
            userIds: selectedRows.map((row) => row.userid),
        });
        hide();
        message.success('同步成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('同步失败，请重试');
        return false;
    }
};

const UserList: React.FC = () => {
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<UserListItem>();
    const [selectedRowsState, setSelectedRows] = useState<UserListItem[]>([]);
    const access = useAccess();
    const rowSelection = access.isSystem
        ? {
            onChange: (_: any, selectedRows: React.SetStateAction<UserListItem[]>) => {
                setSelectedRows(selectedRows);
            },
        }
        : false;
    /** 国际化配置 */
    const columns: ProColumns<UserListItem>[] = [
        {
            title: '所属组织',
            dataIndex: "organizationId",
            valueType: 'select',
            search: access.isSystem,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await organizationSelectList({includeSystem:true});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.organizationId,
                    })) || []
                );
            },
        },
        {
            title: '用户ID',
            dataIndex: 'userid',
            search: false,
            hidden: true,
        },
        {
            title: '所属组织',
            dataIndex: ['organization', 'name'],
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
            hidden: access.isCustom,
        },
        {
            title: '账号',
            dataIndex: 'account',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '显示名',
            dataIndex: 'username',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            valueType: 'text',
            hidden: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '角色',
            dataIndex: 'authority',
            render: (value, record, index) => {
                return <Tag color="blue"> {Object.values(record.authority.authorityName)} </Tag>;
            },
            search: false,
            ellipsis: true, // 关闭自动换行
        },

        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: UserStatusEnum,
            ellipsis: true, // 关闭自动换行
            render: (value, record, index) => {
                let switchStatus = record.status == 1;
                return <Switch
                    disabled={!access.isAdmin}
                    checked={switchStatus}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                    defaultChecked
                    onChange={(checked) => {
                        let title = '是否禁用用户?'
                        let content = '禁用用户后，将不允许登录任何平台和资源'
                        if (record.status == 2) {
                            title = '是否启用用户?'
                            content = '启用用户后，将允许登录任何平台和资源'
                        }
                        confirm({
                            title: title,
                            content: content,
                            onOk() {
                                let msg = handleSwitch(record);
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                                return true;
                            }
                        });
                    }
                    }
                />;

            },
        },
        {
            title: 'uidNumber',
            dataIndex: 'uidNumber',
            valueType: 'text',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: 'Ldap DN',
            dataIndex: 'dn',
            valueType: 'text',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '上次登录时间',
            sorter: true,
            dataIndex: 'lastActiveTime',
            valueType: 'dateTime',
            search: false,
            ellipsis: true, // 关闭自动换行
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            ellipsis: true, // 关闭自动换行
            render: (_, record) => {
                return [
                    <Access accessible={access.isAdmin || false}>
                        <a
                            key="config"
                            onClick={() => {
                                handleUpdateModalVisible(true);
                                setCurrentRow(record);
                            }}
                        >
                            编辑
                        </a>
                    </Access>,
                    <Access accessible={access.isAdmin || false}>
                        <a
                            key="reset"
                            onClick={() => {
                                confirm({
                                    title: '重置密码?',
                                    content: '确认重置账号密码?',
                                    onOk() {
                                        let msg = resetPassword({userid: record.userid});
                                        message.success('重置成功');
                                        if (actionRef.current) {
                                            actionRef.current.reload();
                                        }
                                        return true;
                                    }
                                });
                            }}
                        >
                            重置密码
                        </a>
                    </Access>,
                    <a
                        key="reset"
                        onClick={() => {
                            confirm({
                                title: '同步用户账号信息',
                                content: '确认同步用户账号信息?',
                                onOk() {
                                    let msg = syncLdap({userid: record.userid});
                                    message.success('同步成功');
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                    return true;
                                }
                            });
                        }}
                    >
                        账号同步
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<UserListItem, UserListPagination>
                headerTitle="用户列表"
                actionRef={actionRef}
                rowKey="userid"
                search={{
                    labelWidth: 90,
                    span: 7,
                }}
                scroll={{x: true}}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 新建
                    </Button>,
                ]}
                request={fUserList}
                columns={columns}
                rowSelection={rowSelection}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '账号同步',
                                // icon: <ExclamationCircleFilled />,
                                content: '确认同步账号信息?',
                                onOk() {
                                    handleSyncLdap(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量同步
                    </Button>
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除用户',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除主机用户后，主机将无法SSH登录，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <AddForm
                onSubmit={async (value) => {
                    const success = await handleAdd(value as UserListItem);

                    if (success) {
                        handleModalVisible(false);
                        setCurrentRow(undefined);

                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleModalVisible(false);
                    setCurrentRow(undefined);
                }}
                createModalVisible={createModalVisible}
                values={currentRow || {}}
            />
            <UpdateForm
                onSubmit={async (value) => {
                    const success = await handleUpdate(value, currentRow);

                    if (success) {
                        handleUpdateModalVisible(false);
                        setCurrentRow(undefined);

                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    handleUpdateModalVisible(false);
                    setCurrentRow(undefined);
                }}
                updateModalVisible={updateModalVisible}
                values={currentRow || {}}
            />
        </PageContainer>
    );
};

export default UserList;
